import { getUserInfo, getUserInfoDetail, login } from '@/api/user'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  updatePhoto(state, staffPhoto) {
    state.userInfo.staffPhoto = staffPhoto
  }
}
const actions = {
  async getToken({ commit }, data) {
    const res = await login(data)
    commit('setToken', res)
  },
  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    // console.log(res)
    const res2 = await getUserInfoDetail(res.userId)
    // console.log(res2)
    commit('setUserInfo', {
      ...res,
      staffPhoto: res2.staffPhoto
    })
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    // 退出的时候重置路由
    resetRouter()
    // 重置vuex中的路由信息
    // vue中开启命令空间后，会自动找自己模块的方法
    // 加上root:true 就代表从根命名空间去找
    commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

